package cn.ryanpenn.es.spring;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * SpringJdbcProgram
 *
 * @author pennryan
 */
public class SpringJdbcProgram {

    /**
     * 通过Spring简化JDBC编程示例
     */
    public static void test() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:mem:test");
        dataSource.setUsername("xxx");
        dataSource.setPassword("随便填");

        JdbcTemplate jdbcTem = new JdbcTemplate(dataSource);
        int ret = jdbcTem.update("create table person(id int primary key,first_name varchar(20),last_name varchar(20));");
        if (ret!= -1){
            System.out.println("创建表");

            jdbcTem.execute("insert into person(id,first_name,last_name) values(1,'tom','hanks')");
            System.out.println("写入数据");

            String sql = "select id, first_name, last_name from person where id = ?";
            final Person person = new Person();
            final Object[] params = new Object[]{1};
            jdbcTem.query(sql, params, new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    person.setId(rs.getInt("id"));
                    person.setFirstName(rs.getString("first_name"));
                    person.setLastName(rs.getString("last_name"));
                }
            });
            System.out.println(person);
        }
    }

}
